import fs from 'fs';
import path from 'path';
import { User, Category, Word, ChallengeRecord, PartOfSpeech } from '@/types';

const DATA_DIR = path.join(process.cwd(), 'data');

// 确保数据目录存在
if (!fs.existsSync(DATA_DIR)) {
  fs.mkdirSync(DATA_DIR, { recursive: true });
}

const USERS_FILE = path.join(DATA_DIR, 'users.json');
const CATEGORIES_FILE = path.join(DATA_DIR, 'categories.json');
const WORDS_FILE = path.join(DATA_DIR, 'words.json');
const RECORDS_FILE = path.join(DATA_DIR, 'records.json');
const POS_FILE = path.join(DATA_DIR, 'pos.json');

// 示例文件路径
const USERS_EXAMPLE_FILE = path.join(DATA_DIR, 'users.example.json');
const CATEGORIES_EXAMPLE_FILE = path.join(DATA_DIR, 'categories.example.json');
const WORDS_EXAMPLE_FILE = path.join(DATA_DIR, 'words.example.json');
const RECORDS_EXAMPLE_FILE = path.join(DATA_DIR, 'records.example.json');
const POS_EXAMPLE_FILE = path.join(DATA_DIR, 'pos.example.json');

// 从示例文件复制数据
function copyFromExample(targetFile: string, exampleFile: string, defaultData: any) {
  if (!fs.existsSync(targetFile)) {
    if (fs.existsSync(exampleFile)) {
      // 如果示例文件存在，从示例文件复制
      try {
        const exampleData = fs.readFileSync(exampleFile, 'utf-8');
        fs.writeFileSync(targetFile, exampleData, 'utf-8');
        console.log(`已从示例文件初始化: ${path.basename(targetFile)}`);
      } catch (error) {
        // 如果读取示例文件失败，使用默认数据
        fs.writeFileSync(targetFile, JSON.stringify(defaultData, null, 2), 'utf-8');
      }
    } else {
      // 如果示例文件不存在，使用默认数据
      fs.writeFileSync(targetFile, JSON.stringify(defaultData, null, 2), 'utf-8');
    }
  }
}

// 初始化数据文件
function initFile(filePath: string, defaultData: any) {
  if (!fs.existsSync(filePath)) {
    fs.writeFileSync(filePath, JSON.stringify(defaultData, null, 2), 'utf-8');
  }
}

// 初始化所有数据文件（优先从示例文件复制）
export function initDataFiles() {
  copyFromExample(USERS_FILE, USERS_EXAMPLE_FILE, []);
  copyFromExample(CATEGORIES_FILE, CATEGORIES_EXAMPLE_FILE, []);
  copyFromExample(WORDS_FILE, WORDS_EXAMPLE_FILE, []);
  copyFromExample(RECORDS_FILE, RECORDS_EXAMPLE_FILE, []);
  copyFromExample(POS_FILE, POS_EXAMPLE_FILE, []);
}

// 读取数据
export function readUsers(): User[] {
  initDataFiles();
  try {
    const data = fs.readFileSync(USERS_FILE, 'utf-8');
    return JSON.parse(data);
  } catch {
    return [];
  }
}

export function readCategories(): Category[] {
  initDataFiles();
  try {
    const data = fs.readFileSync(CATEGORIES_FILE, 'utf-8');
    return JSON.parse(data);
  } catch {
    return [];
  }
}

export function readWords(): Word[] {
  initDataFiles();
  try {
    const data = fs.readFileSync(WORDS_FILE, 'utf-8');
    return JSON.parse(data);
  } catch {
    return [];
  }
}

export function readRecords(): ChallengeRecord[] {
  initDataFiles();
  try {
    const data = fs.readFileSync(RECORDS_FILE, 'utf-8');
    return JSON.parse(data);
  } catch {
    return [];
  }
}

export function readPos(): PartOfSpeech[] {
  initDataFiles();
  try {
    const data = fs.readFileSync(POS_FILE, 'utf-8');
    return JSON.parse(data);
  } catch {
    return [];
  }
}

// 写入数据
export function writeUsers(users: User[]) {
  fs.writeFileSync(USERS_FILE, JSON.stringify(users, null, 2), 'utf-8');
}

export function writeCategories(categories: Category[]) {
  fs.writeFileSync(CATEGORIES_FILE, JSON.stringify(categories, null, 2), 'utf-8');
}

export function writeWords(words: Word[]) {
  fs.writeFileSync(WORDS_FILE, JSON.stringify(words, null, 2), 'utf-8');
}

export function writeRecords(records: ChallengeRecord[]) {
  fs.writeFileSync(RECORDS_FILE, JSON.stringify(records, null, 2), 'utf-8');
}

export function writePos(items: PartOfSpeech[]) {
  fs.writeFileSync(POS_FILE, JSON.stringify(items, null, 2), 'utf-8');
}

// 辅助函数：生成ID
export function generateId(): string {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

// 初始化默认分类
export function initDefaultCategories() {
  const categories = readCategories();
  if (categories.length > 0) return;

  const defaultCategories: Category[] = [
    { id: 'primary', name: '小学', parentId: null, path: '小学', level: 1 },
    { id: 'middle', name: '初中', parentId: null, path: '初中', level: 1 },
    { id: 'high', name: '高中', parentId: null, path: '高中', level: 1 },
    { id: 'college', name: '大学', parentId: null, path: '大学', level: 1 },
    { id: 'cet4', name: '四级', parentId: 'college', path: '大学/四级', level: 2 },
    { id: 'cet6', name: '六级', parentId: 'college', path: '大学/六级', level: 2 },
  ];

  writeCategories(defaultCategories);
}

